CSS - tutorial - 29 - media queries

revision:


Content

media queries allow to apply CSS styles depending on a device's general type. syntax targeting media types targeting media features creating complex media queries syntax improvements in Level 4 adding breakpoints typical device breekpoints various examples


media queries allow to apply CSS styles depending on a device's general type.

top

Media queries are used for the following:

To conditionally apply styles with the CSS @media and @import at-rules.

To target specific media for the <style>, <link>, <source>, and other HTML elements with the "media= attribute".

To test and monitor media states using the "Window.matchMedia()" and "EventTarget.addEventListener()" methods.

Example : if the browser window is 600px or smaller, the background color will be lightblue:

            @media only screen and (max-width: 600px) {
                body {
                  background-color: lightblue;
                }
              }
        


syntax

top

A media query is composed of an optional media type and any number of media feature expressions, which may optionally be combined in various ways using logical operators. Media queries are case-insensitive.

        @media not | only mediatype and (expressions) {
            CSS-Code;
          }
    

Media types define the broad category of device for which the media query applies: "all", "print", "screen", "speech".

all : used for all media type devices.

print : used for printers.

screen : used for computer screens, tablets, smart-phones, etc.

speech : used for screenreaders that "reads" the page out loud.

The type is optional (assumed to be all) except when using the "not" or "only" logical operators.

Media features describe a specific characteristic of the user agent, output device, or environment.

Logical operators can be used to compose a complex media query: "not", "and", and "only". You can also combine multiple media queries into a single rule by separating them with commas.

A media query computes to true when the media type (if specified) matches the device on which a document is being displayed and all media feature expressions compute as true. Queries involving unknown media types are always false.


targeting media types

top

Media types describe the general category of a given device. Although websites are commonly designed with screens in mind, you may want to create styles that target special devices such as "printers" or "audio-based screen readers".

For example, this CSS targets printers:

            @media print{
                /* - - */
            }
        

You can also target multiple devices.

For instance, this @media rule uses two media queries to target both screen and print devices:

            @media screen, print{
                /* - - */
            }
        


targeting media features

top

Media features describe the specific characteristics of a given user agent, output device, or environment. For instance, you can apply specific styles to widescreen monitors, computers that use mice, or to devices that are being used in low-light conditions.

This example applies styles when the user's primary input mechanism (such as a mouse) can hover over elements:

            @media (hover: hover){
                /* - - */
            }
        

Many media features are range features, which means they can be prefixed with "min-" or "max-" to express "minimum condition" or "maximum condition" constraints.

For example, this CSS will apply styles only if your browser's viewport width is equal to or narrower than 1250px:

            @media (max-width: 1250px){
                /* - - */
            }
        

If you create a media feature query without specifying a value, the nested styles will be used as long as the feature's value is not zero (or none, in Level 4).

For example, this CSS will apply to any device with a color screen:

            @media (color){
                /* - - */
            }
        


creating complex media queries

top

Creating a media query that depends on multiple conditions needs logical operators to come in: not, and, and only. Furthermore, multiple media queries can be combined into a comma-separated list. This allows to apply the same styles in different situations.

The "and" operator can combine multiple media features into a single media query.

The "not" operator negates a media query, basically reversing its normal meaning.

The "only" operator prevents older browsers from applying the styles.

Combining multiple types or features : The "and" keyword combines a media feature with a media type or other media features.

This example combines two media features to restrict styles to landscape-oriented devices with a width of at least 30vw:

            @media (min-width: 30vw) and (orientation: landscape){
                /* - - */
            }
        

To limit the styles to devices with a screen, the media features can be chained to the screen media type:

            @media screen and (min-height: 30vh) and (orientation: portrait){
                /* - - */
            }
        

Testing for multiple queries : a comma-separated list can be used to apply styles when the user's device matches any one of various media types, features, or states.

For instance, the following rule will apply its styles if the user's device has either a minimum height of 680px or is a screen device in portrait mode:

            @media (min-height: 680px), screen and (orientation: portrait) {
                /* … */
              }
        

Inverting a query's meaning : The "not" keyword inverts the meaning of an entire media query. It will only negate the specific media query it is applied to. (Thus, it will not apply to every media query in a comma-separated list of media queries.) The not keyword can't be used to negate an individual feature query, only an entire media query.

The not is evaluated last in the following query:

            @media not all and (monochrome) {
                    /* … */
            }
            meaning:
                @media not(all and (monochrome)) {
                    /* … */
                }
        


syntax improvements in Level 4

top

The Media Queries Level 4 specification includes some syntax improvements to make media queries using features that have a "range" type - for example width or height - less verbose. Level 4 adds a range context for writing such queries.

For example, using the max- functionality for width we might write the following:

            @media (max-width: 30vw) {
                /* … */
              }
        

In Media Queries Level 4 this can be written as:

            @media (width <= 30vw) {
                /* … */
              }
        

Using min- and max- we might test for a width between two values like so:

            @media (min-width: 30vw) and (max-width: 50vw) {
                /* … */
              }
        

This would convert to the Level 4 syntax as:

            @media (30vw <= width  <= 50vw) {
                /* … */
              }
        


adding breakpoints

top

A breakpoint can be added where certain parts of the design will behave differently on each side of the breakpoint.

Example : when the screen (browser window) gets smaller than 768px, each column should have a width of 100%:

            /* For desktop: */
            .col-1 {width: 8.33%;}
            .col-2 {width: 16.66%;}
            .col-3 {width: 25%;}
            .col-4 {width: 33.33%;}
            .col-5 {width: 41.66%;}
            .col-6 {width: 50%;}
            .col-7 {width: 58.33%;}
            .col-8 {width: 66.66%;}
            .col-9 {width: 75%;}
            .col-10 {width: 83.33%;}
            .col-11 {width: 91.66%;}
            .col-12 {width: 100%;}

            @media only screen and (max-width: 768px) {
                /* For mobile phones: */
                [class*="col-"] {
                    width: 100%;
                }
            }
        

typical device breekpoints

top

There are tons of screens and devices with different heights and widths, so it is hard to create an exact breakpoint for each device. To keep things simple you could target five groups:

            /* Extra small devices (phones, 600px and down) */
            @media only screen and (max-width: 600px) {...}

            /* Small devices (portrait tablets and large phones, 600px and up) */
            @media only screen and (min-width: 600px) {...}

            /* Medium devices (landscape tablets, 768px and up) */
            @media only screen and (min-width: 768px) {...}

            /* Large devices (laptops/desktops, 992px and up) */
            @media only screen and (min-width: 992px) {...}

            /* Extra large devices (large laptops and desktops, 1200px and up) */
            @media only screen and (min-width: 1200px) {...}
        

various examples

top

Example: the web page will have a lightblue background if the orientation is in landscape mode:

            @media only screen and (orientation: landscape) {
                body {
                    background-color: lightblue;
                }
            }
        

Example: if the screen size is 600px wide or less, hide the element

            @media only screen and (max-width: 600px) {
                div.example {
                    display: none;
                }
            }
        

Example: if the screen size is 601px or more, set the font-size of <div> to 80px

            @media only screen and (min-width: 601px) {
                div.example {
                    font-size: 80px;
                }
            }
        

Example: if the screen size is 600px or less, set the font-size of <div> to 30px

            @media only screen and (max-width: 600px) {
                div.example {
                    font-size: 30px;
                }
            }